package com.pphh.demo;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandProperties;
import com.pphh.demo.exception.BlockException;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Please add description here.
 *
 * @author huangyinhuang
 * @date 11/22/2018
 */
public class HystricAsynFlowControl extends FlowControl {

    private HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy;

    public HystricAsynFlowControl(HystrixCommandProperties.ExecutionIsolationStrategy isolationStrategy){
        this.isolationStrategy = isolationStrategy;
    }

    @Override
    public void run() throws BlockException {
        HystrixCommand command = new TestCommand(this, this.isolationStrategy);
        Future<String> fs = command.queue();

        String result = null;
        try {
            result = fs.get(100, TimeUnit.SECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            e.printStackTrace();
        }

        if (TestCommand.FAIL.equals(result)) {
            throw new BlockException("task is blocked by hystrix.");
        }
    }

    public HystrixCommandProperties.ExecutionIsolationStrategy getIsolationStrategy() {
        return isolationStrategy;
    }
}
